﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using readmodel = Meditime.UI;
using System.Collections.Generic;
using System.Threading;

namespace Meditime.UI
{
    public partial class StaffMembers : Form
    {
        StaffMember _selectedStaffMember;

        public StaffMembers()
        {
            InitializeComponent();
        }

        public StaffMember GetStaffMember()
        {
            this.StartPosition = FormStartPosition.CenterScreen;
            btnSelect.Visible = true;
            this.ShowDialog();
            return _selectedStaffMember;
        }

        private void llbAddMember_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                AddEditMember addEdit = new AddEditMember();
                Action command = addEdit.CreateStaffMember();
                if (command != null)
                    SubmitCommand(command);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                RefreshGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void RefreshGrid()
        {
            dgStaffMembers.Columns.Clear();
            dgStaffMembers.Columns.Add("Status", "Loading...");
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (s, e) =>
                {
                    try
                    {
                        e.Result = GetStaffData();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(Common.FormatError(ex));
                    }
                };
            worker.RunWorkerCompleted += PopulateGrid;
            worker.RunWorkerAsync();
        }

        private List<StaffMember> GetStaffData()
        {
            using (ReadModelEntities readmodel = new ReadModelEntities())
            {
                return (from staff in readmodel.StaffMembers
                        select staff).ToList();
            }
        }

        delegate void PopulateGridMethod(object sender, RunWorkerCompletedEventArgs e);
        void PopulateGrid(object sender, RunWorkerCompletedEventArgs e)
        {
            try
            {
                if (dgStaffMembers.InvokeRequired)
                {
                    dgStaffMembers.Invoke(new PopulateGridMethod(PopulateGrid), new object[] { sender, e });
                    return;
                }
                dgStaffMembers.DataSource = e.Result;
                dgStaffMembers.Columns[0].Visible = false;
                btnRefresh.Enabled = true;
            }
            catch (Exception ex)
            {
                CommandNotifier.Instance.WriteToTextBox(Common.FormatError(ex), true);
            }
        }

        private void dgStaffMembers_DoubleClick(object sender, EventArgs e)
        {
            try
            {
                if (dgStaffMembers.SelectedRows.Count == 0) return;
                AddEditMember addEdit = new AddEditMember();

                Action command = addEdit.EditMember(Guid.Parse(dgStaffMembers.SelectedRows[0].Cells["Id"].Value.ToString()));
                if (command != null)
                    SubmitCommand(command);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void SubmitCommand(Action submitCommand)
        {
            dgStaffMembers.Columns.Clear();
            dgStaffMembers.DataSource = null;
            dgStaffMembers.Columns.Add("Status", "Waiting for Command...");
            dgStaffMembers.Columns[0].Width = Convert.ToInt32(dgStaffMembers.Width * 0.9);
            btnRefresh.Enabled = false;
            ThreadPool.QueueUserWorkItem(p =>
            {
                try
                {
                    submitCommand();
                    CommandNotifier.Instance.WriteToTextBox("The Staff Member change completed successfully.");
                }
                catch (Exception ex)
                {
                    if (this.Parent == null)
                    {
                        MessageBox.Show(Common.FormatError(ex));
                    }
                    CommandNotifier.Instance.WriteToTextBox(Common.FormatError(ex), true);
                }
                finally
                {
                    PopulateGrid(this, new RunWorkerCompletedEventArgs(GetStaffData(), null, false));
                }
            });
            CommandNotifier.Instance.WriteToTextBox("The Staff Member change has been submitted.");
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgStaffMembers.SelectedRows.Count == 0) return;
                var selected = dgStaffMembers.SelectedRows[0].DataBoundItem as StaffMember;
                if (selected != null)
                    _selectedStaffMember = selected;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void StaffMembers_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.Parent != null)
                {
                    this.Top = 0;
                    this.Left = 0;
                    this.Width = this.Parent.Width - (CommandNotifier.Instance.Width + 6);
                    this.Height = this.Parent.Height - 4;
                }
                RefreshGrid();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

    }
}
